import axios, {AxiosRequestConfig} from "axios";
import Store from "./store"

export const defaultConfig = {
    headers: {
        "referer": "https://www.mogu.com/",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
    },
}
export const getReq = function (url: string, config: AxiosRequestConfig = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            headers: {
                ...defaultConfig.headers,
                "cookie": Store.getCookies()
            },
            ...config
        }).then(r => {
            let {data} = r;
            let cookies: Array<string> = r.headers['set-cookie'];
            Store.setCookie(cookies);
            let res: Array<string> | null = null
            if (typeof data == 'string' && (res = data.match(/^mwpCb1\((.*)\)$/))) {
                let obj = JSON.parse(res[1]);
                obj.ret == 'FAIL_SYS_TOKEN_NEED_RENEW' ? reject("401") : resolve(obj.data);
            } else {
                resolve(data)
            }
        }).catch(reject)
    })
}